from django.shortcuts import render,redirect
from django.views import View
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from .models import *
import jsonpickle
from utils.code import gene_code,gene_line,gene_text
from django.core.serializers import serialize
from cartapp.cartmanager import SessionCartManager

# Create your views here.

class RegisterView(View):

    def get(self,request):
        return render(request,"register.html")

    def post(self,request):
        # 获取请求参数
        uname = request.POST.get('account','')
        pwd = request.POST.get('password','')

        # 注册用户信息（将数据添加到数据库）
        try:
            user = UserInfo.objects.get(uname=uname,pwd=pwd)
            return render(request,"register.html")
        except UserInfo.DoesNotExist:
            user = UserInfo.objects.create(uname=uname,pwd=pwd)
            # 将注册的用户对象存入session中
            request.session['user'] = jsonpickle.dumps(user)
        
        return redirect('/user/center')
    
class CenterView(View):
    def get(self,request):
        return render(request,"center.html")
    
class LoginView(View):
    def get(self,request):
        reflag = request.GET.get('reflag','')

        return render(request,"login.html",{'reflag':reflag})
    
    def post(self,request):
        uname = request.POST.get('account','')
        pwd = request.POST.get('password','')

        reflag = request.POST.get('reflag','')
        cartitems = request.POST.get('cartitems','')
        totalPrice = request.POST.get('totalPrice','')
        try:
            user = UserInfo.objects.filter(uname=uname,pwd=pwd)
            request.session['user'] = jsonpickle.dumps(user[0])
            
            # 将购物车中的数据迁移到数据库中
            SessionCartManager(request.session).migrateSession2DB()
            if reflag == 'cart':
                return HttpResponseRedirect('/cart/queryAll/')
            elif reflag == 'order':
                return HttpResponseRedirect('/order/?cartitems='+cartitems+'&totalPrice='+totalPrice)
            else:
                return HttpResponseRedirect('/user/center/')
        except UserInfo.DoesNotExist:
            return render(request,"login.html")

class LoadCodeView(View):
    def get(self, request):
        try:
            from captcha.image import ImageCaptcha
            import os
            from pathlib import Path

            BASE_DIR = Path(__file__).resolve().parent.parent

            font_path = os.path.join(BASE_DIR, 'utils', 'Arial.ttf')

            image = ImageCaptcha(fonts=[font_path])

            code = gene_text()
            print(f"Generated code: {code}")  # 打印生成的验证码文本

            imgObj = image.generate(code)

            request.session['session_code'] = code

            return HttpResponse(imgObj, content_type='image/png')
        except Exception as e:
            print(f"Error: {str(e)}")  # 打印错误信息
            return HttpResponse(f"Error: {str(e)}", content_type='text/plain', status=500)

    # def get(self,request):
    #     # 获取图片验证码
    #     imgObj,code = gene_code()
    #     request.session['session_code'] = code
    #     return HttpResponse(imgObj,content_type='image/png')
        
class CheckCodeView(View):
    def get(self,request):
        # 获取请求参数
        code = request.GET.get('code',-1)
        # 获取session中的验证码
        session_code = request.session.get('session_code',-2)
        vflag = False
        if code == session_code:
            vflag = True
        # 返回响应
        return JsonResponse({'vflag':vflag})
    
class LogoutView(View):
    def post(self,request):
        # 清空session中的所有数据
        request.session.flush()

        # 返回响应
        return JsonResponse({'logout':True})
    
class AddressView(View):
    def get(self,request):
        # 获取当前登录用户下的收货地址信息
        # 获取当前登录用户对象
        userstr = request.session.get('user','')
        if userstr:
            user = jsonpickle.loads(userstr)
        
        addr_list = user.address_set.all()

        return render(request,"address.html",{'addr_list':addr_list})
    
    def post(self,request):
        aname = request.POST.get('aname','')
        aphone = request.POST.get('aphone','')
        addr = request.POST.get('addr','')
        # 获取当前登录用户对象
        userstr = request.session.get('user','')
        if userstr:
            user = jsonpickle.loads(userstr)
        Address.objects.create(
            aname=aname,
            aphone=aphone,
            addr=addr,
            userinfo=user,
            isdefault=(lambda count:True if count==0 else False)(user.address_set.count())
        )

        return HttpResponseRedirect('/user/address/')

class LoadAreaView(View):
    def get(self,request):
        pid = request.GET.get('pid',-1)
        if pid == '':
            pid = -1
        else:
            pid = int(pid)
        areaList = Area.objects.filter(parentid=pid)
        # 序列化数据
        jareaList = serialize('json',areaList)
        return JsonResponse({'jareaList':jareaList})
    


def updateDefaultAddr(request):
    addr_id = request.GET.get('addrid',-1)
    addr_id = int(addr_id)
    print(addr_id)
    # 修改数据
    Address.objects.filter(id=addr_id).update(isdefault=True)
    Address.objects.exclude(id=addr_id).update(isdefault=False)

    return HttpResponseRedirect('/user/address/')
